package example;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TcpServer {
    public static void main(String args[]) throws Exception {
        serverThread();
    }
    
    public static void server() {
        try {
            System.out.println("服务端启动，等待连接");
            ServerSocket serverSocket = new ServerSocket(1818);
            Socket socket = serverSocket.accept();

            InputStream inputStream = socket.getInputStream();
            StringBuffer buffer = new StringBuffer();
            byte byt[] = new byte[1];
            int len = 0;
            while ( (len = inputStream.read(byt, 0, byt.length)) != -1 ) {
                String string = new String(byt, 0, len);
                buffer.append(string);
            }
            socket.shutdownInput();
            System.out.println("接收到客户端的消息: " + buffer.toString());

            OutputStream outputStream = socket.getOutputStream();
            outputStream.write("receive!".getBytes());
            socket.shutdownOutput();

            outputStream.close();
            inputStream.close();
            socket.close();
            serverSocket.close();

            System.out.println("服务端断开");
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    
    public static void serverThread() throws Exception {
        ExecutorService executorService = Executors.newCachedThreadPool();
        ServerSocket serverSocket = new ServerSocket(9926);
        while (true) {
            final Socket socket = serverSocket.accept();// 阻塞
            executorService.execute(() -> handler(socket));
        }
        
    }
    
    public static void handler(Socket socket) {
        try {
            InputStream inputStream = socket.getInputStream();
            byte[] bytes = new byte[1024];
            StringBuilder stringBuffer = new StringBuilder();

            while (true) {
                int len = inputStream.read(bytes);//阻塞
                if (len != -1) {
                    String s = new String(bytes, 0, len);
                    stringBuffer.append(s);
                } else {
                    break;
                }
            }
            socket.shutdownInput();
            System.out.println("客户端发送消息:"+stringBuffer);
            
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}





